import axios from 'axios';
import {getToken, removeToken} from "./auth";

if (process.env.NODE_ENV === 'production') {
    axios.defaults.baseURL = 'http://test.xiuyiwenhua.com';
} else {
    axios.defaults.baseURL = 'http://fe.qianchuzihua.test';
    // axios.defaults.baseURL = 'http://test.xiuyiwenhua.com';
}

// create an axios instance
const service = axios.create({
    // baseURL: 'http://fe.qianchuzihua.dev',
    timeout: 20000,
});

// request interceptor
// Do something before request is sent
service.interceptors.request.use(config => {

    // set header auth token
    let token = getToken();
    if (token) {
        config.headers['Authorization'] = 'Bearer ' + token// 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    }

    // config.headers['Content-Type'] = 'application/x-www-form-urlencodeed';
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';

    return config
}, error => {

    return Promise.reject(error)
});


// respone interceptor
service.interceptors.response.use(
    response => {

        // check business code
        // if (response.data.meta.feedback !== undefined && response.data.meta.code !== '000') {
        //     tool.toast.show(viewId, 'server error');
        // }

        // return response.data;
        return Promise.resolve(response.data);
    },
    error => {

        // check login status
        // if (error.response.status == this.globalData.REJECT) {
        //     removeToken();
        //     setTimeout(() => {location.href = '/#/user/login';}, 3000);
        //     // setTimeout(() => {Router.push({name: 'login'});}, 3000);
        // }

        return Promise.reject(error)
    }
);


export default service
